package org.example.fancystudy.ThreadLocalStudy;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author chaigq
 * @version 1.0
 * @date 2023/2/21 14:39
 */
class House{
    int saleCount = 0;
    public synchronized void setSaleCount(){
        ++ saleCount;
    }

    ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);
    public void setThreadLocal(){
        threadLocal.set(1 + threadLocal.get());
    }
}
// 需求2： 5个销售卖完随机数房子，各自独立销售额度，自己业绩按提成走，分灶吃饭，各个销售自己动手，丰衣足食
public class ThreadLocalDemo {
    public static void main(String[] args) throws InterruptedException {
        House house = new House();
        for (int i = 1; i <= 5; i++) {
            new Thread(() -> {
                try {
                    int size = new Random().nextInt(5) + 1;
                    for (int j = 1; j <= size; j++) {
                        // 用于计算各个线程的总数
                        house.setSaleCount();
                        house.setThreadLocal();
                    }
                    System.out.println(Thread.currentThread().getName()+"\t"+"号销售卖出："+house.threadLocal.get());
                }finally {
                    // threadLocal 回收自定义的变量，防止内存泄露，当线程复用的时候，产生异常
                    house.threadLocal.remove();
                }
            }, String.valueOf(i)).start();
        }

        //暂停毫秒,让线程执行完成
        try {
            TimeUnit.MILLISECONDS.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"\t"+"共计卖出多少套： "+house.saleCount);
    }
}
